import ArticleItem from '@/components/ArticleItem';
import { useAppDispatch, useAppSelector } from '@/store';
import { getArticleByIdAction, refreshArticleAction } from '@/store/action/article';
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';
import { map } from 'lodash';
import { useEffect } from 'react';
import styles from './index.module.scss';
type Props = {
  channel_id: number;
  style?: React.CSSProperties;
};

export default function ArticleList({ channel_id, style }: Props) {
  const { artileData } = useAppSelector((state) => state.article);
  const articleList = (artileData[channel_id] || {}).results;
  const pre_timestamp = (artileData[channel_id] || {}).pre_timestamp;

  const dispatch = useAppDispatch();

  useEffect(() => {
    dispatch(getArticleByIdAction(channel_id));
  }, [dispatch, channel_id]);

  const loadMore = async () => {
    await dispatch(getArticleByIdAction(channel_id, Number(pre_timestamp)));
  };

  return (
    <div className={styles.root} style={{ ...style }}>
      <div className="channel-list">
        <PullToRefresh onRefresh={async () => await dispatch(refreshArticleAction(channel_id))}>
          {map(articleList, (item) => (
            <ArticleItem key={item.art_id} data={item} />
          ))}
        </PullToRefresh>

        {!!articleList?.length && <InfiniteScroll loadMore={loadMore} hasMore={!!pre_timestamp} />}
      </div>
    </div>
  );
}
